/* ajax请求函数返回模块
返回值：promise对象（异步返回的数据是response.data）
*/
import axios from 'axios'
import Qs from 'qs'

export default function ajax (url, data = {}, type = 'GET') {
  return new Promise(function (resolve, reject) {
    // 执行异步ajax请求
    let promise
    if (type === 'GET') {
      // 准备url query参数数据
      let dataStr = ''// 数据拼接字符串
      Object.keys(data).forEach(key => {
        dataStr += key + '=' + data[key] + '&'
      })
      if (dataStr !== '') {
        dataStr = dataStr.substring(0, dataStr.lastIndexOf('&'))
        url = url + '?' + dataStr
      }
      promise = axios.get(url)
    } else {
      promise = axios.post(url, Qs.stringify(data), {
        headers: {
          'content-type': 'application/json',
          'X-Request-With': 'XMLHttpRequest',
          'token': window.sessionStorage.getItem('token')
        }
      })
    }

    promise.then(function (response) {
      resolve(response.data)
    }).catch(function (error) {
      reject(error)
    })

    // 成功调用resolve

    // 失败调用reject
  }

  )
}
